<template>
  <div>
  <div style="width: 500px; padding: 50px; margin:50px auto;background: white;border: 1px solid red">
    <h1 style="text-align: center">管理员登陆</h1>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit('form')">登录</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      form: {
        username:"root",
        password:"123456"
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
      }
    }
  },
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {

          let url = 'http://localhost:9088/admins/login';
          console.log('请求路径：' + url);
          console.log('请求参数：');
          console.log(this.form);
        let fromData = this.qs.stringify(this.form)
          this.axios.post(url, fromData).then((response) => {
            console.log('服务器端的响应：');
            console.log(response);
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              // 登录成功，服务器端将响应JWT
              let jwt = responseBody.data;
              console.log('登录成功，服务器端响应的JWT：' + jwt);
              // 使用LocalStorage存储JWT
              localStorage.setItem('jwt', jwt);
              console.log('将JWT数据保存到LocalStorage！');
              // 测试：从LocalStorage中取出JWT
              let localJwt = localStorage.getItem('jwt');
              console.log('测试：从LocalStorage中取出JWT：' + localJwt);
              // 登录成功
              this.$message({
                message: '登录成功！（暂不跳转）',
                type: 'success'
              });
            } else {
              // 密码错误
              this.$message.error(responseBody.message);
            }
          });

        } else {
          alert('参数格式有误，不允许提交！');
          return false;
        }
      });
    }
  }}

</script>

<style>
body{
  background: darkblue !important;
}

</style>